<?php
namespace app\index\controller;
header('Access-Control-Allow-Origin:*');
header("Access-Control-Allow-Headers: Origin, X-Requested-With, Content-Type, Accept"); 

use \think\Request;
use \think\Config;
use \think\Loader;
use \think\Session;
use \think\Db;
class User extends Base
{
	public function index(){
		echo '222';
	}
	//检测用户名
	public function checkusername($username){

		$user=model("homeuser");
		$info = $user ->checkusername($username);
		if($info){
		   $res =array(
		   	'status' => 1,
		   	'info'  => $info
		   );
		   echo json_encode($res);
		   exit;
		}else{
			return false;
		}
	}
    //检测验证码
	public function checkcode($code){
		$phonecode= Session::get('code');
		if($phonecode != $code ){
		   $res =array(
		   	'status' => 1,
		   	'info'  => '验证码错误!'
		   );
			echo json_encode($res);
			exit;
		}else{
			return false;
		}
	}
	//登录
	public function login(){
	    $user=model("homeuser");
		$data = $_POST['userinfo'];
		$response = $user->where(array('username' => $data['username'],'password' => md5($data['password'])))->find();
		if($response){
			$res =array(
				'status' => 0,
				'info' =>$response
			);
		}else{
			$res =array(
				'status' => 1,
				'info' =>'账号密码错误'
			);
		}
		echo json_encode($res);
	}
	//注册
	public function register(){
	    $user=model("homeuser");
		$data = $_POST['userinfo'];
		$result = $this->validate($data,'User');
		if(true !== $result){
		    $res =array(
		    	'status' => 1,
		    	'info'  => $result
		    );
		    echo json_encode($res);
		    exit;
		}
		if($data['repass'] != $data['password']){
		    $res =array(
		    	'status' => 1,
		    	'info'  => '两次密码不一致'
		    );
		    echo json_encode($res);
		    exit;		
		}
		$coderes = $this->checkcode($data['verification']);
		$usernameres = $this->checkusername($data['username']);
		if(!empty($coderes) || !empty($usernameres)){
			$res=array(
		    	'status' => 0,
		    	'info'  => '注册失败!'
		    );
		    echo json_encode($res);
			exit;
		};
		$phoneres = $user->checkphone($data['phone']);
		if($phoneres){
			$res=array(
		    	'status' => 0,
		    	'info'  => $phoneres
		    );
		    echo json_encode($res);
		    exit;
		}
		$newdata=array(
			'username' => $data['username'],
			'password' => md5($data['password']),
			'phone' =>$data['phone'],
			'is_member' =>0 
		);
		$response = $user -> insert($newdata);
		if($response){
			$res=array(
		    	'status' => 0,
		    	'info'  => $newdata
		    );
		}else{
			$res=array(
		    	'status' => 1,
		    	'info'  => '注册失败'
		    );
		}
		echo json_encode($res);
	}
	//手机验证码发送
	public function sendCode() {
		$tel=$_GET['tel'];
		Loader::import('org\TopClient', EXTEND_PATH);
		$c = new \org\TopClient;
		$c->appkey = Config::get("alidayu.App_Key");
		$c->secretKey = Config::get("alidayu.App_Secret");
		$req = new \org\AlibabaAliqinFcSmsNumSendRequest;
		$num=num6_rand();
		$req->setExtend('123456');
		$req->setSmsType("normal");
		$req->setSmsFreeSignName("急速达外卖网");
		$req->setSmsParam("{\"code\":\"$num\"}");
		$req->setRecNum($tel);
		$req->setSmsTemplateCode("SMS_69980562");
		$resp = $c->execute($req);
		Session::set('code',$num);
		$code=Session::get('code');
		$data=array(
			'status' => 1 ,
			'res' => $code
		);
		echo json_encode($data);
	}
	//测试用的
	public function address(){
		if(empty($_GET['uid'])){
          echo json_encode(array('status'=>1,'info'=>'缺少参数'));
		    exit;
		}
		$address=model('address');
		$result=$address->where(array('uid' => $_GET['uid']))->select();
		if($result){
			$res=array(
				'status' =>0,
				'info' => $result
			);
		}else{
			$res=array(
				'status' =>1
			);
		}
		echo json_encode($res);
	}
	//地址添加
	public function addressadd(){
		$data=$_POST['address_data'];
		$result = $this->validate($data,'Address');
		if(true !== $result){
		    $res =array(
		    	'status' => 1,
		    	'info'  => $result
		    );
		    echo json_encode($res);
		    exit;
		}
		$data['create_time']=time();
		$address=model('address');
		$haveval=$address->checkval($data['uid']);
		if($haveval){
			$data['is_default']=1;
		}
		$response=$address->insert($data);
		if($response){
			$res=array(
		    	'status' => 0,
		    );
		}else{
			$res=array(
		    	'status' => 1,
		         'info'  => '提交失败'
		    );
		}
		echo json_encode($res);

	}
	//地址修改
	public function addresssave(){
		$data=$_POST['address_data'];
		$result = $this->validate($data,'Address');
		if(true !== $result){
		    $res =array(
		    	'status' => 1,
		    	'info'  => $result
		    );
		    echo json_encode($res);
		    exit;
		}
		$id=$data['id'];
		unset($data['id']);
		$address=model('address');
		$response=$address->save($data,['id' => $id]);
		if($response){
			$res=array(
		    	'status' => 0,
		    );
		}else{
			$res=array(
		    	'status' => 1,
		         'info'  => '修改失败'
		    );
		}
		echo json_encode($res);
	}
	//设置默认地址
	public function setdefalut(){
		if(empty($_POST['data'])){
		    $res =array(
		    	'status' => 1,
		    	'info'  => '错误提交'
		    );
		    echo json_encode($res);
		    exit;
		}
		$data=$_POST['data'];
		$id=$data['id'];
		$uid=$data['uid'];
		$address=model('address');
		Db::startTrans();
		$response=false;
		try{
		    Db::name('address')->where(array('uid'=>$uid))->update(['is_default'=>0]);
		    $response=Db::name('address')->where(array('id'=>$id))->update(['is_default'=>1]);
		    // 提交事务
		    Db::commit();    
		} catch (\Exception $e) {
		    // 回滚事务
		    Db::rollback();
		}
		if($response){
			$res=array(
		    	'status' => 0,
		    );
		}else{
			$res=array(
		    	'status' => 1,
		         'info'  => '设为默认失败'
		    );
		}
		echo json_encode($res);
	}
	//用户基本信息
	public function queryuser(){
		if(empty($_GET['id'])){
          	echo json_encode(array('status'=>0,'info'=>'缺少参数'));
			exit;
		}
		$id=$_GET['id'];
		$userinfo  = Db::name('homeuser')->where(array('id'=>$id))->find();
		if($userinfo){
			$data = array(
				'status' =>1,
				'info' =>$userinfo
			); 
		}else{
			$data = array(
				'status' =>0
			); 		
		}
		echo json_encode($data);
	}
	//更改用户基本信息
	public function changeuser(){
		$data=$_POST['userinfo'];
		$result = $this->validate($data,'User.edit');
		if(true !== $result){
		    $res =array(
		    	'status' => 0,
		    	'info'  => $result
		    );
		    echo json_encode($res);
		    exit;
		}
		$homeuser=model('homeuser');
		$newdata=$data;
		unset($newdata['id']);
		$userinfo = $homeuser->where(array('id'=>$data['id']))->update($newdata);
		if($userinfo){
			$res=array(
				'status' =>1,
				'info' =>'修改成功'
			);
		}else{
			$res=array(
				'status' =>0,
				'info' =>'修改失败'
			);
		}
		echo json_encode($res);
	}
	//查看天气
	public function weather(){
		$ip=$_SERVER['REMOTE_ADDR'];
		$city=$this->GetIpLookup($ip);
		$url='http://api.avatardata.cn/WeatherWord/City?key=96fd473d087547b4b51161b69e3b7118&city='.$city;
		$weather = file_get_contents($url);
		echo $weather;
	}
	//查询城市
	public function GetIpLookup($ip = ''){  
	    if($ip == ''){
	        $url = "http://int.dpool.sina.com.cn/iplookup/iplookup.php?format=json";
	        $ip=json_decode(file_get_contents($url),true);
	        $data = $ip;
	    }else{
	        $url="http://ip.taobao.com/service/getIpInfo.php?ip=".$ip;
	        $ip=json_decode(file_get_contents($url));   
	        if((string)$ip->code=='1'){
	           return false;
	        }
	        $data = (array)$ip->data;
	    }
	    
	    return $data['city']; 
	} 
}
